package pers.mihao.quickstream.common.util;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author mihao
 * @since 2021/6/30 20:03
 */
public class ThreadPoolNameUtil {

    private static Map<String, AtomicInteger> map = new HashMap<>(16);
    private static Map<String, ThreadFactory> threadFactoryMap = new HashMap<>(16);

    public static ThreadFactory getThreadFactory(String key) {
        ThreadFactory threadFactory = threadFactoryMap.get(key);
        if (threadFactory != null) {
            return threadFactory;
        }
        threadFactory = r -> {
            Thread thread = new Thread(r);
            thread.setName(getThreadName(key));
            return thread;
        };
        threadFactoryMap.put(key, threadFactory);
        return threadFactory;
    }

    /**
     * 获取现场的名字
     *
     * @param key
     * @return
     */
    public static String getThreadName(String key) {
        AtomicInteger integer = map.computeIfAbsent(key, k -> new AtomicInteger(0));
        return key + "-" + integer.incrementAndGet();
    }

}
